package com.xf.kafkatest.test;

import org.apache.kafka.clients.producer.Partitioner;
import org.apache.kafka.common.Cluster;
import org.apache.kafka.common.PartitionInfo;

import java.util.List;
import java.util.Map;

public class MyPartitioner implements Partitioner {

    @Override
    public int partition(String topic, Object key, byte[] keyBytes, Object value, byte[] valueBytes, Cluster cluster) {

        // 获取当前 topic 所有可用的分区信息
        List<PartitionInfo> partitionInfos = cluster.availablePartitionsForTopic(topic);

        // 如果没有可用分区，返回 0（理论上不会发生）
        if (partitionInfos == null || partitionInfos.isEmpty()) {
            return 0;
        }

        // 固定返回第一个 partition
        return partitionInfos.get(0).partition();
    }

    @Override
    public void close() {

    }

    @Override
    public void configure(Map<String, ?> configs) {

    }
}
